﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Castle.Windsor;

namespace Pipeline.Middleware.Functional
{
    public interface IApplicationBuilder
    {
        IWindsorContainer Container { get; }

        IApplication Build();

        void Use(Func<RequestDelegate, RequestDelegate> request);
    }

    public class ApplicationBuilder : IApplicationBuilder
    {
        private readonly List<Func<RequestDelegate, RequestDelegate>> _middlewares;

        public ApplicationBuilder(IWindsorContainer container)
        {
            Contract.Requires(container!=null,"container!=null");

            Container = container;
            _middlewares=new List<Func<RequestDelegate, RequestDelegate>>();
        }

        public IWindsorContainer Container { get; private set; }

        public IApplication Build()
        {
            RequestDelegate request = context => context;

            _middlewares.Reverse();

            foreach (var middleware in _middlewares)
            {
                request = middleware(request);
            }

            return new Application(request);
        }

        public void Use(Func<RequestDelegate,RequestDelegate> middleware)
        {
            Contract.Requires(middleware!=null,"middleware!=null");

            _middlewares.Add(middleware);
        }

       
    }
}